package com.example.terminalservice.exception;

import cn.hutool.core.util.StrUtil;
import com.example.terminalservice.common.CodeEnum;
import com.example.terminalservice.common.Result;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 28142
 * @description 全局异常处理器
 * @date 2023/8/4 17:04
 */
@RestControllerAdvice
public class MyExceptionHandler {
    /**
     * 自定义异常处理
     * @author 杨雨盛
     * @date 2023/8/5 10:34
     * @param e
     * @return com.example.terminalservice.common.Result
     */
    @ExceptionHandler(MyException.class)
    public Result handler(MyException e) {
        return Result.error(e.getCode(), e.getMessage());
    }

    /**
     * 参数校验 @RequestBody @Valid 配合使用
     * @author 杨雨盛
     * @date 2023/8/5 10:34
     * @param e
     * @return com.example.terminalservice.common.Result
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handler2(MethodArgumentNotValidException e) {
        return Result.error(CodeEnum.CODE_401.getCode(), e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 参数校验
     * @author 杨雨盛
     * @date 2023/8/5 10:38
     * @param e
     * @return com.example.terminalservice.common.Result
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result handler3(ConstraintViolationException  e) {
        List<String> msgList = new ArrayList<>();
        for (ConstraintViolation<?> constraintViolation : e.getConstraintViolations()) {
            msgList.add(constraintViolation.getMessage());
        }
        String msg = StrUtil.join(";", msgList.toArray());
        return Result.error(CodeEnum.CODE_401.getCode(), msg);
    }

    /* @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result handler4(MissingServletRequestParameterException e) {
        return Result.error(CodeEnum.CODE_401.getCode(), e.getMessage());
    } */
}
